﻿using System;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace WindowsFormsApplication24
{
    public class JsonHelper
    {
        public static string JsonToString<T>(T value)
        {
            var vStream = new MemoryStream();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            serializer.WriteObject(vStream, value);
            byte[] jsondata = new byte[vStream.Length];
            vStream.Position = 0;
            if (vStream.Read(jsondata, 0, jsondata.Length) != jsondata.Length)
                throw new Exception("读取出错");
            return Encoding.UTF8.GetString(jsondata);
        }

        public static T StringToJson<T>(string text)
        {
            byte[] jsondata = Encoding.UTF8.GetBytes(text);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            var vStream = new MemoryStream(jsondata);
            return (T)serializer.ReadObject(vStream);
        }  
    }
}